<template>
  <Drawer
    placement="right"
    :closable="true"
    v-model="visible"
    width="400"
    scrollable
    @on-close="cancel"
  >
    <template #header>
      <div class="flex flex-col justify-between">
        <div class="flex items-center mb-4 gap-x-2">
          <img src="~@/assets/images/icon_http.png" class="w-6 h-6" alt="Start icon" />
          <div class="flex flex-col gap-y-1">
            <p class="text-lg font-semibold text-black">{{ title }}</p>
          </div>
        </div>
        <div class="text-sm text-gray-500">用于发送API请求,从接口返回数据</div>
      </div>
    </template>

    <CommonCollapse title="API" tip="API接口的地址">
      <!-- <template #right>
        <Button type="text" size="small">导入cURL</Button>
      </template> -->

      <div class="flex items-center">
        <Select v-model="form.reqmethod">
          <Option v-for="(item, index) in REQ_TYPE_OPTIONS" :key="index" :value="item"
            >{{ item }}
          </Option>
        </Select>
      </div>

      <div class="flex items-center">
        <Input
          v-model="form.url"
          type="textarea"
          :rows="3"
          :placeholder="`请输入接口的URL,可以使用'{{'引用变量`"
          style="margin-top: 8px"
        />
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="请求参数" tip="设置调用接口时需要传入的参数详情">
      <template #right>
        <Button
          type="primary"
          size="small"
          icon="md-add"
          @click="addInput('reqparamlist')"
        ></Button>
      </template>
      <div class="panel-table">
        <div class="panel-table-header">
          <div class="name" style="width: 150px">变量名</div>
          <div class="name">变量值</div>
        </div>
        <div class="panel-table-list">
          <Form v-if="form" ref="formEl" :model="form" label-position="top">
            <div
              class="flex items-center mb-4"
              v-for="(item, index) in form.reqparamlist"
              :key="index"
            >
              <div class="panel-table-item" style="width: 160px">
                <FormItem
                  :key="index"
                  :prop="'reqparamlist.' + index + '.varname'"
                  :rules="{
                    required: true,
                    message: '变量名不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input v-model="item.varname" placeholder="输入变量名" size="small" />
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 100px; margin-right: 0">
                <FormItem>
                  <Select size="small" v-model="item.vartype" disabled>
                    <Option v-for="item in BE_TYPE_LIST" :value="item.value" :key="item.value">{{
                      item.label
                    }}</Option>
                  </Select>
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <FormItem
                  :prop="'reqparamlist.' + index + '.varparam'"
                  :rules="{
                    required: true,
                    message: '变量值不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    size="small"
                    v-model="item.varparam"
                    check-strictly
                    placeholder="输入参数值"
                  />
                </FormItem>
              </div>
              <div class="panel-table-item btn" @click="removeInput('reqparamlist', index)">
                <Icon type="md-remove" />
              </div>
            </div>
          </Form>
        </div>
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="请求头" tip="配置HTTP请求头,用于传递认证信息,内容类型等关键参数">
      <template #right>
        <Button type="primary" size="small" icon="md-add" @click="addInput('reqheadlist')"></Button>
      </template>
      <div class="panel-table">
        <div class="panel-table-header">
          <div class="name" style="width: 150px">变量名</div>
          <div class="name">变量值</div>
        </div>
        <div class="panel-table-list">
          <Form v-if="form" ref="formEl" :model="form" label-position="top">
            <div
              class="flex items-center mb-4"
              v-for="(item, index) in form.reqheadlist"
              :key="index"
            >
              <div class="panel-table-item" style="width: 160px">
                <FormItem
                  :key="index"
                  :prop="'reqheadlist.' + index + '.varname'"
                  :rules="{
                    required: true,
                    message: '变量名不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input v-model="item.varname" placeholder="输入变量名" size="small" />
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 100px; margin-right: 0">
                <FormItem>
                  <Select size="small" v-model="item.vartype">
                    <Option v-for="item in BE_TYPE_LIST" :value="item.value" :key="item.value">
                      {{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <FormItem
                  :prop="'reqheadlist.' + index + '.varparam'"
                  :rules="{
                    required: true,
                    message: '变量值不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    size="small"
                    v-model="item.varparam"
                    check-strictly
                    placeholder="输入参数值"
                  >
                  </Input>
                </FormItem>
              </div>
              <div class="panel-table-item btn" @click="removeInput('reqheadlist', index)">
                <Icon type="md-remove" />
              </div>
            </div>
          </Form>
        </div>
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse v-if="form" title="鉴权" tip="用于验证请求者的身份和权限">
      <template #right>
        <Switch v-model="form.isauthority"></Switch>
      </template>

      <template v-if="form.isauthority">
        <div class="panel-table-list">
          <Form ref="formEl" :model="form" label-position="top">
            <FormItem style="margin-bottom: 12px">
              <Select size="small" v-model="form.bearertype">
                <Option v-for="item in dicGather" :value="item.id" :key="item.id">
                  {{ item.name }}
                </Option>
              </Select>
            </FormItem>

            <div v-if="form.bearertype === dicGather[0].id" class="flex items-center mb-4">
              <div class="panel-table-item" style="width: 160px">
                <FormItem>
                  <Input placeholder="token" size="small" readonly />
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 100px; margin-right: 0">
                <FormItem>
                  <Select size="small" placeholder="String" disabled></Select>
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <FormItem>
                  <Input size="small" v-model="form.token" check-strictly placeholder="输入参数值">
                  </Input>
                </FormItem>
              </div>
            </div>

            <template v-else>
              <div class="flex items-center mb-4">
                <div class="panel-table-item" style="width: 160px">
                  <FormItem>
                    <Input placeholder="key" size="small" readonly />
                  </FormItem>
                </div>
                <div class="panel-table-item" style="width: 100px; margin-right: 0">
                  <FormItem>
                    <Select size="small" disabled placeholder="String"></Select>
                  </FormItem>
                </div>
                <div class="panel-table-item" style="width: 180px">
                  <FormItem>
                    <Input
                      size="small"
                      v-model="form.customizevo.key"
                      check-strictly
                      placeholder="输入参数值"
                    >
                    </Input>
                  </FormItem>
                </div>
              </div>

              <div class="flex items-center mb-4">
                <div class="panel-table-item" style="width: 160px">
                  <FormItem>
                    <Input placeholder="value" size="small" readonly />
                  </FormItem>
                </div>
                <div class="panel-table-item" style="width: 100px; margin-right: 0">
                  <FormItem>
                    <Select size="small" disabled placeholder="String"></Select>
                  </FormItem>
                </div>
                <div class="panel-table-item" style="width: 180px">
                  <FormItem>
                    <Input
                      size="small"
                      v-model="form.customizevo.value"
                      check-strictly
                      placeholder="输入参数值"
                    >
                    </Input>
                  </FormItem>
                </div>
              </div>

              <div class="flex items-center mb-4">
                <div class="panel-table-item" style="width: 160px">
                  <FormItem>
                    <Input placeholder="Add To" size="small" readonly />
                  </FormItem>
                </div>

                <div class="panel-table-item" style="width: 280px">
                  <FormItem>
                    <Select size="small" v-model="form.customizevo.addTo">
                      <Option v-for="item in ADD_TO_OPTIONS" :value="item" :key="item">
                        {{ item }}
                      </Option>
                    </Select>
                  </FormItem>
                </div>
              </div>
            </template>
          </Form>
        </div>

        <!-- <div class="flex items-center">
          <Input v-model="form.customizevo.addTo" placeholder="120" />
        </div> -->
      </template>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="请求体" tip="请求体数据，设置要发送的具体内容">
      <!-- <div class="flex items-center"> -->
      <Select size="small" v-model="form.reqbodytype" @on-change="form.reqbodyparam = ''">
        <Option v-for="item in BODY_TYPE_OPTIONS" :value="item.value" :key="item.value">
          {{ item.label }}
        </Option>
      </Select>
      <!-- </div> -->

      <Input
        v-if="['x-www-form-urlencoded', 'raw text', 'form-data', 'JSON'].includes(form.reqbodytype)"
        style="margin-top: 8px"
        v-model="form.reqbodyparam"
        placeholder="请输入请求体参数"
      />

      <div v-if="form.reqbodytype === 'binary'" class="upload-btn">
        <Icon type="ios-folder-outline" size="16"></Icon>

        <Upload :before-upload="beforeUpload">
          <template v-if="!form.reqbodyparam">
            <Icon type="md-cloud-upload" size="16"></Icon>
            <div>上传文件</div>
          </template>
          <div class="file-context" v-else @click.stop>
            <span>{{ form.filename }}</span>
            <Icon v-if="!fileLoading" type="ios-close" size="20" @click="form.filename = form.reqbodyparam = ''" />
            <Icon v-else type="ios-loading" size="20" />
          </div>
        </Upload>
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="超时设置(秒)">
      <div class="flex items-center">
        <InputNumber style="width: 100%" :min="1" v-model="form.timeout" />
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="重试次数">
      <div class="flex items-center">
        <InputNumber style="width: 100%" :min="0" v-model="form.retrycount" />
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="输出" tip="大模型运行完成后生成的内容">
      <el-tree default-expand-all :data="form.outputList">
        <template #default="{ node, data }">
          <div class="panel-table">
            <div class="flex items-center">
              <span class="text-sm">{{ data.varname }}</span>

              <div class="text-bg-normal">{{ data.vartype }}</div>
            </div>
          </div>
        </template>
      </el-tree>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="异常忽略" tip="异常设置">
      <template #right>
        <Switch v-model="form.isexepignore" />
      </template>

      <div class="flex items-center">忽略异常并在异常发生时使用默认输出替代</div>

      <div v-if="form.isexepignore" class="w-full h-52" style="margin-top: 10px">
        <p>默认输出</p>
        <MonacoEditor v-model="form.defoutput" />
      </div>
    </CommonCollapse>
  </Drawer>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useNode } from '@vue-flow/core'
import CommonCollapse from '@/components/CommonCollapse/index.vue'
import MonacoEditor from '../../monaco-editor.vue'
import { BE_TYPE_LIST, BODY_TYPE_OPTIONS } from '../../lib/constant'
import { flowUpload } from '@/api/modules/flow'

import { dicCode } from '@/api/modules/flow'

const REQ_TYPE_OPTIONS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']

const DEFAULT_LLM_TABS = [
  {
    label: '单次',
    value: 0
  },
  {
    label: '批处理',
    value: 1
  }
]
const OUTPUT_FORMAT_OPTIONS = [
  {
    label: '输出格式文本',
    value: 'text'
  },
  {
    label: '输出格式Markdown',
    value: 'markdown'
  },
  {
    label: '输出格式JSON',
    value: 'JSON'
  }
]

const ADD_TO_OPTIONS = ['Header', 'Query']
const node = useNode()
const props = defineProps({
  form: {
    type: Object,
    default: () => {}
  },
  title: {
    type: String,
    default: '输出'
  },
  dicGather: Array
})

const emit = defineEmits(['add', 'remove', 'cancel'])

const visible = ref(false)
const showModal = ref(false)

// 组件的增删
const addInput = (listKey) => {
  emit('add', listKey)
}
const removeInput = (listKey, index) => {
  if (listKey == 'outputList' && index == 0) return
  emit('remove', listKey, index)
}
const init = () => {
  visible.value = true
}
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const fileLoading = ref(false)
const beforeUpload = (file) => {
  props.form.filename =  file.name
  fileLoading.value = true
  flowUpload({
    upload: file,
    id: node.id
  }).then(({data})=>{
    props.form.reqbodyparam = data.data.fileurl
  }).finally(()=>{
    fileLoading.value = false
  })

  return false
}

defineExpose({
  init
})
</script>

<style scoped lang="scss">
.ivu-input-wrapper {
  :deep(.ivu-input) {
    resize: none;
    // margin-top: 8px;
  }
}
</style>

<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';
.upload-btn {
  display: flex;
  align-items: center;
  border: 1px solid #cfd2df;
  border-radius: 4px;
  height: 32px;
  margin-top: 8px;
  .ivu-icon-ios-folder-outline {
    padding: 0 4px;
    border-right: 1px solid #cfd2df;
    height: 100%;
    line-height: 32px;
  }
  .ivu-upload {
    height: 100%;
    flex: 1;
    :deep(.ivu-upload-select) {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 12px;
    }
  }
  .file-context {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    padding: 0 8px;
    background-color: #d3d7e5;
    >span{
      @include text-ellipsis();
      width: 108px;
    }
    .ivu-icon-ios-close {
      margin-left: 4px;
      &:hover {
        opacity: 0.8;
      }
    }

    .ivu-icon-ios-loading{
      animation: rotateAnimation .8s linear infinite;
    }
  }
}
.panel-table-header {
  align-items: center;
  display: flex;
  gap: 4px;
  padding: 0 4px;

  .name {
    width: 120px;
    margin-right: 6px;
    box-sizing: content-box;
  }
  .center {
    text-align: center;
  }
}

:deep(.ivu-form-item-error-tip) {
  font-size: 12px;
}
.panel-table-item {
  height: 30px;
  margin-right: 6px;
  &.center {
    text-align: center;
  }
  &.btn {
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    margin-left: 12px;
    height: 22px;
  }
}
.ivu-drawer-body {
  height: calc(100vh - 90px);
}
.el-tree-node__content {
  margin-top: 16px;
}

:deep(.ivu-input)[readonly]::placeholder {
  color: #515a6e;
}
</style>
